package com.umeox.moto.common.livebroadcast

import android.content.BroadcastReceiver
import android.content.Context
import android.content.Intent
import android.content.IntentFilter
import androidx.annotation.MainThread
import androidx.lifecycle.LiveData
import com.umeox.moto.common.log.Logger
import com.umeox.moto.common.utils.AppUtils

/**
 * Created by Rambo 2021/8/23
 * Describe:
 */
class WatchStateLiveData : LiveData<String?>() {

    private val mIntentFilter: IntentFilter = IntentFilter()


    private val watchStateReceiver: WatchStateReceiver = WatchStateReceiver()

    override fun onActive() {
        mIntentFilter.addAction("com.wherecom.intent.action.UNBOUND")
        mIntentFilter.addAction("com.wherecom.intent.action.ENABLE_STUDYMODE")
        AppUtils.getApp().registerReceiver(watchStateReceiver, mIntentFilter)
    }

    override fun onInactive() = AppUtils.getApp().unregisterReceiver(watchStateReceiver)

    private class WatchStateReceiver : BroadcastReceiver() {
        override fun onReceive(context: Context?, intent: Intent?) {
            Logger.e("onReceive->action=${intent?.action}")
            get().postValue(intent?.action)
        }

    }

    companion object {

        private lateinit var sInstance: WatchStateLiveData

        @MainThread
        fun get(): WatchStateLiveData {
            sInstance = if (::sInstance.isInitialized) sInstance else WatchStateLiveData()
            return sInstance
        }
    }

}